<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" top="3%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="书名" prop="title">
        <el-input v-model="formData.title" placeholder="请输入书名" />
      </el-form-item>
      <el-form-item label="isbn编号" prop="isbn">
        <el-input v-model="formData.isbn" placeholder="请输入isbn编号" @input="onIsbnInput">
          <template #append>
            <el-button
              v-if="showAutoCompleteBtn"
              type="primary"
              :loading="autoCompleteLoading"
              @click="autoCompleteBookInfo"
            >
              信息补全
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="出版社" prop="publisher">
        <el-input v-model="formData.publisher" placeholder="请输入出版社" />
      </el-form-item>
      <el-form-item label="出版时间" prop="pubDate">
        <el-date-picker
          v-model="formData.pubDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="选择出版时间"
        />
      </el-form-item>
<!--      <el-form-item label="出版年限" prop="pubYear">-->
<!--        <el-date-picker-->
<!--          v-model="formData.pubYear"-->
<!--          type="date"-->
<!--          value-format="x"-->
<!--          placeholder="选择出版年限"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="页数" prop="pageCount">
        <el-input v-model="formData.pageCount" placeholder="请输入页数" />
      </el-form-item>
<!--      <el-form-item label="流程状态" prop="applyStatus">-->
<!--        <el-select v-model="formData.applyStatus" placeholder="请选择流程状态">-->
<!--          <el-option-->
<!--            v-for="dict in getStrDictOptions(DICT_TYPE.BK_BOOK_APPLY_STATUS)"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="书籍状态" prop="storeStatus">
        <el-radio-group v-model="formData.storeStatus">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.BK_BOOK_STORE_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>

      </el-form-item>
<!--      <el-form-item label="入库时间" prop="storeTime">-->
<!--        <el-date-picker-->
<!--          v-model="formData.storeTime"-->
<!--          type="date"-->
<!--          value-format="x"-->
<!--          placeholder="选择入库时间"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="捐献人id" prop="donor">-->
<!--        <el-input v-model="formData.donor" placeholder="请输入捐献人id" />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="当前持有人id" prop="nowHolder">-->
<!--        <el-input v-model="formData.nowHolder" placeholder="请输入当前持有人id" />-->
<!--      </el-form-item>-->
      <el-form-item label="捐赠人" prop="donor">
        <el-select
          v-model="formData.donor"
          placeholder="请输入筛选捐赠人"
          filterable
          remote
          reserve-keyword
          :remote-method="searchUsers"
          :loading="userSearchLoading"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="`${user.name || user.nickname || '未知用户'} (${user.mobile || '未知号码'})`"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" :rows="2" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { LwBookApi, LwBookVO } from '@/api/bk/lwbook'
import { ignorableWatch } from '@vueuse/core'
import * as UserApi from '@/api/member/user'

/** 来往书籍 表单 */
defineOptions({ name: 'LwBookForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const showAutoCompleteBtn = ref(false) // 是否显示自动补全按钮
const autoCompleteLoading = ref(false) // 自动补全加载状态
const userSearchLoading = ref(false) // 用户搜索加载状态
const userOptions = ref<UserApi.UserVO[]>([]) // 用户选项列表
const formData = ref({
  title: undefined,
  isbn: undefined,
  publisher: undefined,
  pubDate: undefined,
  pubYear: undefined,
  pageCount: undefined,
  applyStatus: undefined,
  storeStatus: "1",
  storeTime: undefined,
  donor: undefined,
  nowHolder: undefined,
  remark: undefined,
})
const formRules = reactive({
  title: [{ required: true, message: '书名不能为空', trigger: 'blur' }],
  isbn: [{ required: true, message: 'isbn不能为空', trigger: 'blur' }],
  storeStatus: [{ required: true, message: '书籍状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await LwBookApi.getLwBook(id)
      // 加载数据后检查ISBN是否有效，决定是否显示自动补全按钮
      if (formData.value.isbn) {
        showAutoCompleteBtn.value = isValidIsbn(formData.value.isbn)
      }
      // 如果有捐赠人ID，加载对应的用户信息
      if (formData.value.donor) {
        await loadDonorInfo(formData.value.donor)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as LwBookVO
    if (formType.value === 'create') {
      await LwBookApi.createLwBook(data)
      message.success(t('common.createSuccess'))
    } else {
      await LwBookApi.updateLwBook(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    title: undefined,
    isbn: undefined,
    publisher: undefined,
    pubDate:  undefined,
    pubYear: undefined,
    pageCount: undefined,
    applyStatus: undefined,
    storeStatus: "1",
    storeTime: undefined,
    donor: undefined,
    nowHolder: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
  showAutoCompleteBtn.value = false
  userOptions.value = []
}

/** ISBN格式验证 */
const isValidIsbn = (isbn: string) => {
  if (!isbn) return false
  // 移除所有非数字和非X字符
  const cleanIsbn = isbn.replace(/[^0-9X]/gi, '')
  // ISBN-10: 10位数字，最后一位可能是X
  // ISBN-13: 13位数字
  return cleanIsbn.length === 10 || cleanIsbn.length === 13
}

/** ISBN输入监听 */
const onIsbnInput = (value: string) => {
  showAutoCompleteBtn.value = isValidIsbn(value)
}

/** 自动补全书籍信息 */
const autoCompleteBookInfo = async () => {
  if (!formData.value.isbn || !isValidIsbn(formData.value.isbn)) {
    message.warning('请输入正确的ISBN编号')
    return
  }

  autoCompleteLoading.value = true
  try {
    const bookInfo = await LwBookApi.getIsbn(formData.value.isbn)
    if (bookInfo) {
      formData.value.pubDate = undefined

      // 补全书籍信息，但不覆盖已有的非空值
      if (bookInfo.title && !formData.value.title) {
        formData.value.title = bookInfo.title
      }
      if (bookInfo.publisher && !formData.value.publisher) {
        formData.value.publisher = bookInfo.publisher
      }
      if (bookInfo.pubDate && !formData.value.pubDate) {
        // 处理日期格式，确保能正确写入日期控件
        try {
          // 如果是标准日期格式，转换为YYYY-MM-DD格式
          const date = new Date(bookInfo.pubDate)
          if (!isNaN(date.getTime())) {
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            //@ts-ignore
            formData.value.pubDate = `${year}-${month}-${day}`
          } else {
            // 如果已经是YYYY-MM-DD格式，直接使用
            formData.value.pubDate = bookInfo.pubDate
          }
        } catch (error) {
          console.warn('日期格式转换失败:', error)
          formData.value.pubDate = bookInfo.pubDate
        }
      }
      if (bookInfo.pageCount && !formData.value.pageCount) {
        formData.value.pageCount = bookInfo.pageCount
      }
      message.success('书籍信息补全成功')
    }
  } catch (error) {
    console.error('获取书籍信息失败:', error)
    message.error('获取书籍信息失败，请检查ISBN编号是否正确')
  } finally {
    autoCompleteLoading.value = false
  }
}

/** 搜索用户 */
const searchUsers = async (query: string) => {
  if (!query || query.trim().length < 1) {
    userOptions.value = []
    return
  }

  userSearchLoading.value = true
  try {
    const params = {
      pageNo: 1,
      pageSize: 20,
      name: query.trim(),
      status: 0 // 只搜索正常状态的用户
    }
    const data = await UserApi.getUserPage(params)
    userOptions.value = data.list || []
  } catch (error) {
    console.error('搜索用户失败:', error)
    userOptions.value = []
  } finally {
    userSearchLoading.value = false
  }
}

/** 加载捐赠人信息 */
const loadDonorInfo = async (donorId: number) => {
  try {
    const user = await UserApi.getUser(donorId)
    if (user) {
      userOptions.value = [user]
    }
  } catch (error) {
    console.error('加载捐赠人信息失败:', error)
  }
}
</script>
